package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.annotation.Idempotent;
import com.example.demo.service.IdempotentService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class CustomInterceptor implements HandlerInterceptor {

    @Resource
    private IdempotentService idempotentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            Method method = ((HandlerMethod) handler).getMethod();

            if (method.isAnnotationPresent(Idempotent.class)){
                String tokenName = request.getHeader("tokenName");
                String tokenValue = request.getHeader("tokenValue");
                System.out.println(tokenName+"  "+tokenValue);

                if (!idempotentService.checkToken(tokenName, tokenValue)){
                    JSONObject object=new JSONObject();
                    object.put("code","111111");
                    object.put("status","error");
                    object.put("msg","token 检验失败");
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println(object);

                    return false;
                }
            }
        }

        return true;
    }
}
